package com.cn.Dao;

import com.cn.base.BaseDao;
import com.cn.entity.Newsclass;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class NewsclassDao {
    public List<Newsclass> findAll() throws SQLException {
        Connection connection = BaseDao.getConn();
        try {
            Statement state=connection.createStatement();
            String sql="select * from newspaper";
            ResultSet rs = state.executeQuery(sql);
            List<Newsclass> newsclasses = getList(rs);
            connection.close();
            return newsclasses;
        }catch (Exception e){
            throw e;
        }
    }
    private static Newsclass getClass(ResultSet resultSet){
        try {
            Newsclass newsclass = new Newsclass();
            while (resultSet.next()){
                newsclass.setId(resultSet.getInt(1));
                newsclass.setNclass(resultSet.getString(2));
            }
            return newsclass;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    private List<Newsclass> getList(ResultSet resultSet){
        try {
            List<Newsclass> newsclasses=new ArrayList<>();
            while (resultSet.next()){
                Newsclass newsclass = new Newsclass();
                newsclass.setId(resultSet.getInt(1));
                newsclass.setNclass(resultSet.getString(2));
                newsclasses.add(newsclass);
            }
            return newsclasses;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String IdToName(int id) throws SQLException {
        Connection connection = BaseDao.getConn();
        try {
            Statement state=connection.createStatement();
            String sql="select * from newspaper where NEWS_ID='"+id+"'";
            ResultSet rs = state.executeQuery(sql);
            Newsclass newsclass = getClass(rs);
            connection.close();
            return newsclass.getNclass();
        }catch (Exception e){
            throw e;
        }
    }
    public Newsclass findById(Integer id) throws SQLException {
        Connection connection = BaseDao.getConn();
        try {
            Statement state=connection.createStatement();
            String sql="select * from newspaper where NEWS_ID='"+id+"'";
            ResultSet rs = state.executeQuery(sql);
            Newsclass newsclasse = getClass(rs);
            connection.close();
            return newsclasse;
        }catch (Exception e){
            throw e;
        }
    }
}
